/**
 * Created by MIS on 2016/7/1.
 */
(function () {
    var effect = function (source, target) {
        this.source = source;
        this.target = target;
        this.setting = {
            fps: 0.05
        }
        // 竖直方向加速度
        this.g = 0.24;
        // 小球上抛的距离
        this.gap = 40;

        // 速度
        this.v = (function () {
            var left = this.source.offsetLeft;
            var top = this.source.offsetTop;
            var targetLeft = this.target.offsetLeft;
            var targetTop = this.target.offsetTop;
            var h = targetTop - top;
            var s = left - targetLeft;
            var v = {
                x: 0,// 纵向初始速度值
                y: 0// 横向速度值
            };

            // 小球抛到顶部所需要的时间
            var t1 = Math.sqrt(2 * this.gap / this.g);
            // 小球从顶部落下所需要的时间
            var t2 = Math.sqrt(2 * (this.gap + h) / this.g);

            v.x = s / (t1 + t2);
            v.y = -this.g * t1;
            return v;
        }.bind(this))();

        this.render()
    }

    effect.prototype = {
        render: function () {
            var fps = this.setting.fps;
            var dist = document.createElement("div");
            dist.className = this.source.className;
            dist.style.background = "#f00";
            dist.style.zIndex = "-1";
            document.body.appendChild(dist);

            this.timer = setInterval(function () {
                var left = dist.offsetLeft;
                var top = dist.offsetTop;
                var targetLeft = this.target.offsetLeft;
                var targetTop = this.target.offsetTop;

                this.v["y"] += this.g;
                var x = left - this.v["x"];
                var y = top + this.v["y"];

                if (y >= targetTop) {
                    clearInterval(this.timer);
                    document.body.removeChild(dist);
                }
                dist.style.left = x + "px";
                dist.style.top = y + "px";

            }.bind(this), (1 / fps));
        }
    };

    effect.init = function (source, target) {
        new this(source, target)
    }

    window["Effect"] = effect;
})();

window.onload = function () {
    var source = document.getElementById("source");
    source.onclick = function () {
        Effect.init(source, document.getElementById("dist"));
    }
};
